package com.bh.ly.oa.activity;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bh.ly.oa.R;
import com.bh.ly.oa.util.AsyncTaskFactory;
import com.bh.ly.oa.util.Config;

public class UploadfileActivity extends Activity {
	/*
	 * 变量声明 filename：上传后在服务器上的文件名称 uploadFile：要上传的文件路径 actionUrl：服务器上对应的程序路径
	 */

	private String uploadFile = Environment.getExternalStorageDirectory() + "/temp.jpg";
	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";
	private TextView mText1;
	private Button mButton;
	private UploadFileAsyncTask uploadFileAsyncTask;
	private ImageView imgView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.uploadfile);

		mText1 = (TextView) findViewById(R.id.myText2);
		mText1.setText("文件路径：\n" + uploadFile);
		/* 设置mButton的onClick事件处理 */
		mButton = (Button) findViewById(R.id.myButton);
		mButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				uploadFile();
			}
		});

		ImageButton button = (ImageButton) findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
				startActivityForResult(intent, PHOTOHRAPH);
			}

		});

		ImageButton backButton = (ImageButton) findViewById(R.id.back_button);
		backButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});
		
		imgView = (ImageView) findViewById(R.id.imageView);
		if(new File(uploadFile).exists()){
			imgView.setImageBitmap(BitmapFactory.decodeFile(uploadFile));
		}
	}

	@Override
	public void onDetachedFromWindow() {
		if (this.uploadFileAsyncTask != null) {
			this.uploadFileAsyncTask.cancel(true);
			this.uploadFileAsyncTask.detachActivity();
		}

		super.onDetachedFromWindow();
	}

	/* 上传文件至Server的方法 */
	private void uploadFile() {

		if (this.uploadFileAsyncTask != null) {
			this.uploadFileAsyncTask.detachActivity();
			this.uploadFileAsyncTask.cancel(true);
			this.uploadFileAsyncTask = null;
		}
		this.uploadFileAsyncTask = new UploadFileAsyncTask();
		this.uploadFileAsyncTask.attachActivity(this);

		this.mButton.setEnabled(false);
		this.mButton.setText(R.string.str_button_uploading);

		AsyncTaskFactory factory = new AsyncTaskFactory();
		factory.build().execute(this.uploadFileAsyncTask);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK) {

			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
				Log.v("TestFile", "SD card is not avaiable/writeable right now.");
				return;
			}

			if (resultCode == NONE)
				return;

			// 拍照
			if (requestCode == PHOTOHRAPH) {

				// 设置文件保存路径这里放在跟目录下

				File picture = new File(uploadFile);

				startPhotoZoom(Uri.fromFile(picture));
			}
			if (data == null)
				return;
			// 读取相册缩放图片
			if (requestCode == PHOTOZOOM) {
				startPhotoZoom(data.getData());
			}
			// 处理结果
			if (requestCode == PHOTORESOULT) {

				Bundle extras = data.getExtras();

				if (extras != null) {

					Bitmap photo = extras.getParcelable("data");

					ByteArrayOutputStream stream = new ByteArrayOutputStream();

					photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)压缩文件

					imgView.setImageBitmap(photo);
				}
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");

		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);

		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);

		intent.putExtra("aspectY", 1);

		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 64);

		intent.putExtra("outputY", 64);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTORESOULT);
	}

	private class UploadFileAsyncTask extends AsyncTask<String, Void, String> {
		private Activity activity;

		public void attachActivity(Activity activity) {
			this.activity = activity;
		}

		public void detachActivity() {
			this.activity = null;
		}

		@Override
		protected String doInBackground(String... arg0) {
			HttpURLConnection httpURLConnection = null;
			StringBuffer result = new StringBuffer();
			try {
				String end = "\r\n\r\n";
				String newLine = "\r\n";
				String twoHyphens = "--";
				String boundary = "******";
				URL url = new URL(Config.domain + Config.uploadfileUrl);
				httpURLConnection = (HttpURLConnection) url.openConnection();
				httpURLConnection.setDoInput(true);
				httpURLConnection.setDoOutput(true);
				httpURLConnection.setUseCaches(false);
				httpURLConnection.setRequestMethod("POST");
				httpURLConnection.setConnectTimeout(50000);
				httpURLConnection.setReadTimeout(50000);
				httpURLConnection.setRequestProperty("Charset", "UTF-8");
				httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
				httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
				httpURLConnection.connect();

				DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
				dos.writeBytes(twoHyphens + boundary + newLine);
				String contentDis = "Content-Disposition: form-data;name=\"suppliercode\"" + end + "600002" + newLine;
				dos.writeBytes(contentDis);
				dos.writeBytes(twoHyphens + boundary + newLine);

				contentDis = "Content-Disposition: form-data;name=\"certificate_type\"" + end + "201" + newLine;
				dos.writeBytes(contentDis);
				dos.writeBytes(twoHyphens + boundary + newLine);

				contentDis = "Content-Disposition: form-data;name=\"enddate\"" + end + "2013-07-11" + newLine;
				dos.writeBytes(contentDis);
				dos.writeBytes(twoHyphens + boundary + newLine);

				contentDis = "Content-Disposition: form-data;name=\"uploadType\"" + end + "html5" + newLine;
				dos.writeBytes(contentDis);
				dos.writeBytes(twoHyphens + boundary + newLine);

				contentDis = "Content-Disposition: form-data;name=\"uploadfile\";" + "filename=\"100238_201_148.JPG\"" + newLine;
				dos.writeBytes(contentDis);

				contentDis = "Content-Type: image/jpeg" + end;
				dos.writeBytes(contentDis);

				FileInputStream fis = new FileInputStream(uploadFile);
				byte[] buffer = new byte[8192]; // 8k
				int count = 0;
				while ((count = fis.read(buffer)) != -1) {
					dos.write(buffer, 0, count);
				}
				fis.close();
				dos.writeBytes(end);
				dos.writeBytes(twoHyphens + boundary + twoHyphens + newLine);
				dos.flush();
				dos.close();

				int code = httpURLConnection.getResponseCode();
				result.append(code);
				Log.e("sys", "code = " + code);
				if (code != 200) {
					return code + "";
				}

				System.out.println("UploadfileActivity upload file ..............");
				InputStream is = httpURLConnection.getInputStream();
				System.out.println("UploadfileActivity getInputStream ..............");
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				String line = null;
				while ((line = br.readLine()) != null) {
					System.out.println("UploadfileActivity readLine.............." + line);
				}
				is.close();

			} catch (Exception e) {
				e.printStackTrace();
				Log.d("UploadfileActivity", "exception=======" + e.getMessage());
				return "-1";
			} finally {
				if (httpURLConnection != null) {
					httpURLConnection.disconnect();
				}
			}
			Log.d("UploadfileActivity", "result=======" + result);
			return result.toString();
		}

		@Override
		protected void onPostExecute(String code) {
			super.onPostExecute(code);
			mButton.setText(R.string.str_button);
			mButton.setEnabled(true);

			if (this.activity == null) {
				return;
			}

			if (code == null || code.length() == 0 || "-1".equals(code)) {
				Toast.makeText(this.activity, this.activity.getString(R.string.upload_file_error), Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this.activity, this.activity.getString(R.string.upload_file_success), Toast.LENGTH_LONG).show();
			}
		}
	}

	private String getBoundry() {
		StringBuffer _sb = new StringBuffer();
		for (int t = 1; t < 12; t++) {
			long time = System.currentTimeMillis() + t;
			if (time % 3 == 0) {
				_sb.append((char) time % 9);
			} else if (time % 3 == 1) {
				_sb.append((char) (65 + time % 26));
			} else {
				_sb.append((char) (97 + time % 26));
			}
		}
		return _sb.toString();
	}

}
